package com.qzl.common.netty.handler.strategy;

import com.qzl.common.netty.annotation.MessageType;
import com.qzl.common.netty.config.ChatConfig;
import com.qzl.common.netty.config.UserConfig;
import com.qzl.common.netty.handler.MessageHandler;
import com.qzl.common.netty.message.Message;
import com.qzl.common.netty.model.UserModel;
import com.qzl.common.netty.utis.ResponseUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

/**
 * @author: qzl
 * @date : 2025/6/24 14:34
 * @description:
 */
@Slf4j
@MessageType(messageType = ChatConfig.CHAT_MESSAGE)
public class ChatHandler implements MessageHandler {
    @Override
    public void handle(ChannelHandlerContext ctx, Message message) {
        log.info("开始处理聊天消息:{}", message);
        String token = message.getToken();
        UserModel userModel = UserConfig.tokenUserMap.get(token);
        String to = message.getTo();
        ChannelHandlerContext channel = UserConfig.userChannelMap.get(to);
        if (channel == null){
            message.setContent("用户不在线");
            ResponseUtils.sendChannelResponse(ctx, message);
            return;
        }
        Message response = new Message();
        BeanUtils.copyProperties(message, response);
        response.setMessageType((int) ChatConfig.WEBSOCKET_MESSAGE);
        response.setFrom(userModel.getUsername());
        ResponseUtils.sendChannelResponse(channel, response);
    }
}
